package com.mec.fileTransfer.core;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 接收文件的集合，，其中可通过map存放文件编号为键，具体单个文件资源（ReceiveFileModel）对象为值
 * 的键值对，其中提供添加、查找（通过文件名逐个查找，返回其文件编号，此处可用equals方法进行优化）
 * 得到未接收完的文件资源的块列表字符串。
 */
public class ReceiveFileSet {
	private Map<Integer, ReceiveFileModel> fileMap;

	private long totalReceiveBytes;//暂时无用
	
	public ReceiveFileSet() {
		fileMap = new ConcurrentHashMap<>();
	}
	
	void addFile(Integer fileId, ReceiveFileModel rfm) throws Exception {
		ReceiveFileModel receiveFileModel = fileMap.get(fileId);
		if(receiveFileModel != null) {
			throw new Exception("文件编号所在的资源已经存在，请勿重复添加！");
		}
		
		fileMap.put(fileId, rfm);
	}
	
	int getFileNo(String fileName) {
		for (int fileNo : fileMap.keySet()) {
			ReceiveFileModel file = fileMap.get(fileNo);
			if (file.equals(fileName)) {
				return fileNo;
			}
		}
		
		return -1;
	}
	
	ReceiveFileModel getReceiveFile(Integer fileId) {
		return fileMap.get(fileId);
	}

	protected Map<Integer, ReceiveFileModel> getFileMap() {
		return fileMap;
	}
	
	
	String getUnreceivedFileBlockList() {
		StringBuffer res = new StringBuffer();
		
		for (int fileId : fileMap.keySet()) {
			ReceiveFileModel rfm = fileMap.get(fileId);
			res.append(fileId).append(':')
				.append(rfm.getAbsolutePath())
				.append(rfm.getFilePath());
			
			List<FileBlockInfo> blockList =
					rfm.getUbi().getBlockList();
			for (FileBlockInfo br : blockList) {
				res.append("\n\t").append(br);
			}
			res.append('\n');
		}
		
		return res.toString();
	}
	
	
	long getTotalReceiveBytes() {
		return totalReceiveBytes;
	}
	
	int getTotalReceiveFiles() {
		return fileMap.size();
	}


	
}
